package com.example.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bookstore.common.BaseContext;
import com.example.bookstore.common.PageResult;
import com.example.bookstore.common.Result;
import com.example.bookstore.dto.OrdersRequest;
import com.example.bookstore.dto.QueryOrderParamsDto;
import com.example.bookstore.entity.*;
import com.example.bookstore.mapper.*;
import com.example.bookstore.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrdersItemMapper ordersItemMapper;
    @Autowired
    BookMapper bookMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    AddresseeMapper addresseeMapper;
    @Autowired
    CartMapper cartMapper;
    @Override
    @Transactional
    public Result createOrders(OrdersRequest ordersRequest, String type) {
        Orders orders = new Orders();
            createOrder(ordersRequest, orders);
            List<Cart> carts = ordersRequest.getCarts();
            for (int i = 0; i < carts.size(); i++) {
                OrdersItem ordersItem = new OrdersItem();
                ordersItem.setOrdersId(orders.getId());
                Cart cart = carts.get(i);
                int quantity = cart.getQuantity();
                ordersItem.setQuantity(quantity);
                ordersItem.setBookId(cart.getBookId());
                Book book = bookMapper.selectById(cart.getBookId());
                if (book.getInventory()< quantity){//购买数大于库存数
                    return Result.error(book.getBookName()+"库存不足，请重新下单");
                }
                ordersItemMapper.insert(ordersItem);
                book.setInventory(book.getInventory()- quantity);//扣减库存
                book.setSales(book.getSales()+quantity);//增加销量
                if (book.getInventory()<=0){//库存小于或等于0
                    book.setStatus(-1);//状态改为下架
                }
                bookMapper.updateById(book);
                cartMapper.deleteById(cart.getId());//删除该购物车项
            }
        return Result.success(orders.getId());
    }

    @Override
    public PageResult<Orders> selectByPageAndCondition(int pageSize, int currentPage, QueryOrderParamsDto params) {
        Page<Orders> page=new Page<>(currentPage,pageSize);
        LambdaQueryWrapper<Orders> qw=new LambdaQueryWrapper<>();
        qw.like(!StringUtils.isEmpty(params.getName()),Orders::getName,params.getName());
        qw.like(!StringUtils.isEmpty(params.getNo()),Orders::getNo,params.getName());
        if (!StringUtils.isEmpty(params.getUsername())){
            List<Integer> ids=userMapper.selectLikUserName("%"+params.getUsername()+"%");
            if (ids.size()==0){
                qw.in(Orders::getUserId,-1);//模糊查询不到数据
            }else {
                qw.in(Orders::getUserId,ids);
            }
        }
        qw.eq(!StringUtils.isEmpty(params.getStatus()),Orders::getStatus,params.getStatus());
        qw.ge(!StringUtils.isEmpty(params.getCreateDate1()),Orders::getCreatTime,params.getCreateDate1());
        qw.le(!StringUtils.isEmpty(params.getCreateDate2()),Orders::getCreatTime,params.getCreateDate2());
        qw.ge(!StringUtils.isEmpty(params.getPayDate1()),Orders::getPayTime,params.getPayDate1());
        qw.le(!StringUtils.isEmpty(params.getPayDate2()),Orders::getPayTime,params.getPayDate2());
        qw.ge(!StringUtils.isEmpty(params.getDeliveryDate1()),Orders::getDeliveryTime,params.getDeliveryDate1());
        qw.le(!StringUtils.isEmpty(params.getDeliveryDate2()),Orders::getDeliveryTime,params.getDeliveryDate2());
        qw.ge(!StringUtils.isEmpty(params.getSignDate1()),Orders::getSignTime,params.getSignDate1());
        qw.le(!StringUtils.isEmpty(params.getSignDate2()),Orders::getSignTime,params.getSignDate2());
        qw.orderByDesc(Orders::getCreatTime);
        Page<Orders> ordersPage = orderMapper.selectPage(page, qw);
        List<Orders> records = ordersPage.getRecords();
        records.forEach(item->{
            User user = userMapper.selectById(item.getUserId());
            item.setUsername(user.getUsername());
        });
        long total = ordersPage.getTotal();
        PageResult<Orders> result=new PageResult<>(records,total,currentPage,pageSize);
        return result;
    }

    @Override
    public Result getOrderAddress(Integer id) {
        Orders orders = orderMapper.selectById(id);
        int addresseeId = orders.getAddresseeId();
        Addressee addressee = addresseeMapper.selectById(addresseeId);
        return Result.success(addressee);
    }
    @Override
    public Result getOrderDetail(Integer id) {
        LambdaQueryWrapper<OrdersItem> qw=new LambdaQueryWrapper<>();
        qw.eq(OrdersItem::getOrdersId,id);
        List<OrdersItem> ordersItems = ordersItemMapper.selectList(qw);
        ordersItems.forEach(item->{
            Book book = bookMapper.selectById(item.getBookId());
            item.setBookImg(book.getBookImg());
            item.setBookName(book.getBookName());
            item.setBookPrice(book.getPrice());
        });
        return Result.success(ordersItems);
    }

    @Override
    public Result cancelOrder(Integer id) {
        Orders orders = orderMapper.selectById(id);
        String status = orders.getStatus();
        LambdaQueryWrapper<OrdersItem> qw=new LambdaQueryWrapper<>();
        qw.eq(OrdersItem::getOrdersId,id);
        ordersItemMapper.delete(qw);
        orderMapper.deleteById(id);
        return Result.success("已取消订单");
    }

    @Override
    public Result updateStatus(Integer ordersId, String status) {
        Orders orders = orderMapper.selectById(ordersId);
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        switch (status){
            case "pay":
                orders.setStatus("待发货");
                orders.setPayTime(sdf.format(now));
                break;
            case "delivery":
                orders.setStatus("运输中");
                orders.setDeliveryTime(sdf.format(now));
                break;
            case "signed":
                orders.setStatus("已签收");
                orders.setSignTime(sdf.format(now));
                break;
            default:
                return Result.error("未知状态");
        }
        orderMapper.updateById(orders);
        return Result.success("更新订单状态成功");
    }

    @Override
    public Result submitAddress(Integer ordersId,Integer addresseeId) {
        Orders orders = orderMapper.selectById(ordersId);
        orders.setAddresseeId(addresseeId);
        orderMapper.updateById(orders);
        return Result.success("订单地址提交成功");
    }

    @Override
    public Result updateAppraise(Integer ordersId) {
        Orders orders = orderMapper.selectById(ordersId);
        orders.setIsAppraise(1);
        orderMapper.updateById(orders);
        return Result.success("该订单已评论");
    }

    private  void createOrder(OrdersRequest ordersRequest, Orders orders) {
        Date now = new Date();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
        String format1 = sdf1.format(now);
        String timestamp = String.valueOf(System.currentTimeMillis());
        String orderNo=format1+timestamp;
        orders.setNo(orderNo);
        orders.setStatus("未付款");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        orders.setCreatTime(sdf2.format(now));
        orders.setName(ordersRequest.getName());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setTotalPrice(ordersRequest.getTotalPrice());
        orders.setBookImg(ordersRequest.getBookImg());
        orders.setIsAppraise(0);
        orderMapper.insert(orders);
    }
}
